package com.example.beikeyigou.untils;

import android.content.Context;
import android.content.SharedPreferences;

import com.example.beikeyigou.login.UserBean;

/*
* 用户登录成功后将信息保存到本地
* */
public class SaveUserUtils {

    public static UserBean.DataBean data = null;
    public static boolean saveUserToMemory(UserBean.DataBean dataBean){
        data = dataBean;
        return true;
    }

    public static boolean saveUserToFile(Context context, UserBean.DataBean dataBean){
        //数据私有，其他应用不可访问
        //获得共享参数对象
        SharedPreferences sharedPreferences = context.getSharedPreferences("user",Context.MODE_PRIVATE);
        //获得编辑对象
        SharedPreferences.Editor editor = sharedPreferences.edit();

        //开始写入数据
        editor.putInt("id",dataBean.getId());
        editor.putString("phone",dataBean.getPhone());
        editor.putString("password",dataBean.getPassword());
        editor.putString("name",dataBean.getName());
        editor.putString("address",dataBean.getAddress());
        editor.putString("nickname",dataBean.getNickname());
        editor.putString("question",dataBean.getQuestion());
        editor.putString("answer",dataBean.getAnswer());

        editor.commit();
        saveUserToMemory(dataBean);
        return true;
    }

    //从文件中获取用户数据
    public static UserBean.DataBean getUserFromFile(Context context){
        SharedPreferences sharedPreferences = context.getSharedPreferences("user",Context.MODE_PRIVATE);

        int id = sharedPreferences.getInt("id",-1);
        String phone =  sharedPreferences.getString("phone","");
        String password = sharedPreferences.getString("password","");
        String name = sharedPreferences.getString("name","");
        String address =  sharedPreferences.getString("address","");
        String nickname = sharedPreferences.getString("nickname","");
        String question = sharedPreferences.getString("question","");
        String answer = sharedPreferences.getString("answer","");

        UserBean.DataBean bean = new UserBean.DataBean();
        bean.setId(id);
        bean.setPhone(phone);
        bean.setPassword(password);
        bean.setName(name);
        bean.setAddress(address);
        bean.setNickname(nickname);
        bean.setQuestion(question);
        bean.setAnswer(answer);

        return bean;

    }

    public static UserBean.DataBean getUserInfo(Context context){
        if (data != null){
            return data;
        }

        UserBean.DataBean user = getUserFromFile(context);
        if (user.getId() != -1){
            data = user;
            return data;
        }

        return null;
    }

    //删除用户信息
    public static void deleteUserINfo(Context context){
        SharedPreferences sharedPreferences = context.getSharedPreferences("user",Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear();
        editor.commit();
        data = null;

    }


}
